<template>
  <div class="online-inquiry layout-media-box">
    <div class="my-user-box">
      <div class="l-panel content">
        <div class="remote-title">会诊页</div>
        <div style="width: 100%;display: flex;justify-content: center;max-height: 700px;overflow:hidden;">
          <div style="min-width: 500px;margin-right: 10px;">
            <el-card>
              <el-descriptions title="详情" :column="3" border label-width="100px">
                <el-descriptions-item label="姓名">{{ patientObj.patientName}}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ patientObj.patientSex === 1 ? '男' : '女'}}</el-descriptions-item>
                <el-descriptions-item label="年龄">{{ patientObj.patientAge }}</el-descriptions-item>
                <el-descriptions-item label="目前诊断">
                  {{ applyForm.diagnosis }}
                </el-descriptions-item>
                <el-descriptions-item label="主诉">
                  {{ applyForm.mainSuit }}
                </el-descriptions-item>
                <el-descriptions-item label="会诊目的">
                  {{ applyForm.rcsPurpose }}
                </el-descriptions-item>
                <el-descriptions-item label="简要病史及诊治过程" :span="3">
                  <span> {{ applyForm.presentIllness }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="过敏史" :span="3">
                  <span> {{ applyForm.historyPresentIllness }}</span>
                  <el-button type="text" style="margin-left: 12px" @click="handleHistoryPresentIllness">编辑</el-button>
                </el-descriptions-item>
                <el-descriptions-item label="会诊诊断" :span="3">
                  <span> {{ applyForm.diagnosis }}</span>
                  <el-button v-if="isExpert" type="text" style="margin-left: 12px" @click="handleDiagnosis">编辑</el-button>
                </el-descriptions-item>

                <el-descriptions-item label="会诊意见" :span="3">
                  <span> {{ applyForm.remark }}</span>
                  <el-button v-if="isExpert" type="text" style="margin-left: 12px" @click="handleRemark">编辑</el-button>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
            <div style="height: 10px"></div>
            <el-card>
              <div
                  class="l-flex l-row-between operate"
              >
                <div class="start-item" @click="checkCase">
                  <img src="@/assets/img/remote/view.png" alt="" />
                  查询病历
                </div>
                <div class="start-item" @click="senImage">
                  <img src="@/assets/img/remote/pic.png" alt="" />
                  发送图片
                  <ImageUpload class="consult-upload" ref="uploadPic" :upload-params="ossParams" :multiple="false" @change="val => handleChangeUpload(val, 'imageUrl')"></ImageUpload>
                </div>
                <div class="start-item" @click="remoteVideo">
                  <img src="@/assets/img/remote/video_disabled.png" alt="" />
                  远程影像</div>
                <div class="start-item" @click="closeRemote" v-if="isExpert">
                  <img src="@/assets/img/remote/end.png" alt="" />
                  结束会诊</div>
              </div>
            </el-card>
          </div>
          <div style="min-width: 750px;flex-grow: 1">
            <el-card class="box-card" style="height: 100%">
<!--            <div style="text-align: right;padding: 12px 0">-->
<!--              <el-button type="primary" size="mini" @click="inviteUserJoinRoom(true)">发起视频</el-button>-->
<!--            </div>-->
            <div class="l-flex-1 video-page meeting-box">
              <AgoraVideo :inviteList="inviteList" :applyForm="applyForm" v-if="agoraConfig.appId" :agoraConfig="agoraConfig">
              </AgoraVideo>
              <div class="video-right-top" style="min-height: 100%">
                <div class="chat-box video-right-bottom" style="min-height: 400px">
                  <div class="chat-content" id="scrollContent" style="height: 340px">
                    <div v-for="(item,index) in chatRoomMsgList" :key="index">
                      <p class="chat-head">
                        <span :class="trueName !== item.msgUserName ? 'chat-color' :''">[{{ item.msgUserName }}]</span>
                        <span>{{item.msgDate}}</span>
                      </p>
                      <div class="chat-msg" v-if="item.msgType == 1" @contextmenu.prevent="openMenu(item,$event)">
                        <viewer style="display:inilne-block;">
                          <img :src="item.msgText" width="100" title="点击预览">
                        </viewer>
                      </div>
                      <p class="chat-msg" v-if="item.msgType == 2" @contextmenu.prevent="openMenu(item,$event)">{{item.msgText}}</p>
                      <el-alert v-if="item.msgType == 5" class="chat-alert" :title="item.msgText" type="info" center :closable="false"> </el-alert>
                      <ul class="chat-withdraw" v-if="isWithdraw && item.msgType != 4" :style="{left:left+'px',top:top+'px'}">
                        <li @click="withdrawHandle(item.msgDate)">撤回</li>
                        <li @click="isWithdraw = false">取消</li>
                      </ul>
                    </div>
                  </div>
                  <el-row class="chat-btn" type="flex" justify="space-between">
                    <el-input size="small" class="btn-input" v-model="sendMsgToPatient" @keyup.enter.native="doctorSendMsg">
                      <el-button slot="append" size="small" type="primary" @click="doctorSendMsg">发送</el-button>
                    </el-input>
                  </el-row>
                </div>
              </div>
            </div>
          </el-card>
          </div>
        </div>
      </div>
    </div>
    <!-- 查看病历组件 -->
    <CaseHistory ref="caseHistory"></CaseHistory>
    <!-- 背景云 -->
  </div>
</template>
<script>
import CaseHistory from "../case-history";
import AgoraVideo from "./AgoraVideo3";
import ImageUpload from "@/components/image-upload/image-upload";
export default {
  components: {
    CaseHistory,
    AgoraVideo,
    ImageUpload
  },
  data() {
    return {
      ossParams: {},
      applyForm: {},
      patientObj: {},
      chatRoomMsgList: [],
      friendId: "",
      isWithdraw: false,
      logId: '',
      sendMsgToPatient: '',
      doctorList: [],
      inviteList: [],
      agoraConfig: {
        appId: '',
        token: '',
        channel: '',
        // appId: "3252d76fde2e46668cb0fd11d4e61ff3", //你的AppId
        // token: "007eJxTYNgnOSuXf2uNSmf7tdTX368mlNmruMc/bPr47FMX7/MdFaIKDMZGpkYp5mZpKalGqSZmZmYWyUkGaSmGhikmqWaGaWnGynds0hsCGRnecPuxMDJAIIjPzGBuacHAAACOwh+G", // 根据房间号生成的token(房间号和token对应)
        // channel: "798", //频道号
        uid: '' //uid必须为数字类型
      }
    };
  },
  computed: {
    trueName() {
      return this.$authInfo.getUser().trueName;
    },
    isExpert() {
      const adminUserInfoStr = this.$getStore('adminUserInfo')
      if (!adminUserInfoStr) return false
      let adminUserInfo = JSON.parse(adminUserInfoStr)
      // 专家 isExpert
      return  adminUserInfo.type === 'D-E'
    },
    //在computed方法声明并存储到vuex
    getWsMsg() {
      return this.$store.state.webSocketMsgRemoteMsg;
    },
    inviteUserJoinRoom() {
      let data = {
        receiverID: this.applyForm.inquiryPatientId, // 邀请人id
        receiverType: 'P', // 邀请人类型
        roomId: this.$route.query.id, // 房间id
        message: '邀请你加入会诊', // 邀请消息
        packageType: 2, // 包类型
        timestamp: new Date().getTime(), // 时间戳
      }
      this.$setWsRemote.send(2, data);
    }
  },
  watch: {
    //监听
    getWsMsg(data, val) {
      if (data != "pong" && data != "") {
        let packageType = data.code;
        switch (packageType) {
          case 1:
            if (data.configuration) {
              this.agoraConfig = {
                appId: data.configuration.appId || '',
                token: data.configuration.sig || '',
                channel: this.$route.query.id,
                uid: data.userId,
                // appId: '3252d76fde2e46668cb0fd11d4e61ff3', // 替换为你的 Agora AppID
                // channel: '998',
                // token: "007eJxTYLDIkdi5se5kuZjoxe0dby4sbNRufLla+1fKunvVSsYtu/YrMBgbmRqlmJulpaQapZqYmZlZJCcZpKUYGqaYpJoZpqUZ73nnmt4QyMiwK/IxMyMDBIL4zAyWlhYMDAC1IyD5", // 根据房间号生成的token(房间号和token对应)
              }
              console.log('data.configuration',data.configuration);
            }
            console.log('登录成功',this.agoraConfig)

            /**
             * 登录成功
             * 任意人都可以创建会诊
             */
            if (this.applyForm.status === 2) {
              this.createRoom()
            }
            // 循环邀请医生、专家入会
            this.inviteDoctorJoinRoom()
            this.inviteUserJoinRoom()
            // 邀请病人加入
            this.invitePatientJoinRoom()
            break
          case 4:
            console.log('消息', data)
            // 解析消息
              this.chatRoomMsgList.push({
                msgUserName: data.sender,
                msgText: data.content,
                msgDate: this.formatDate(new Date(data.timestamp)),
                msgType: data.contentType,
              });

            this.scrollContentBottom();
            break
        }
      }
    },
    isWithdraw(value) {
      if (value) {
        document.body.addEventListener("click", this.closeMenu);
      } else {
        document.body.removeEventListener("click", this.closeMenu);
      }
    }
  },
  methods: {
    handleChangeUpload(val, key) {
      console.log(val, key)
      let data = {
        content: val,
        packageType: 4,
        contentType: 1,
        roomId: this.$route.query.id,
        timestamp: new Date().getTime()
      }
      this.$setWsRemote.send(4, data);
    },
    getDetail() {
      this.$ajax.getConsultationChatRecord({
        roomId: this.$route.query.id
      }).then(res => {
        this.chatRoomMsgList = res.data.map(item => {
          return {
            msgUserName: item.msgUserName,
            msgText: item.content,
            msgDate: item.createTime,
            msgType: item.contentType,
          }
        })
        this.scrollContentBottom();
      })
      this.$ajax.getMyConsultationList({
      }).then(res => {
        // 0已取消 1待审核 2审核通过 3会诊中 4已结束
        // map
        let statusMap = {
          0: "已取消",
          1: "待审核",
          2: "审核通过",
          3: "会诊中",
          4: "已结束"
        }
        let data = res.data.find(item => item.id == this.$route.query.id) || {}
        if (data.diagnosis) {
          data.diagnosis = JSON.parse(data.diagnosis).map(item => item.diagnosis).join("、");
        }
        if (data.expertDoctorList) {
          let expertDoctorName = data.expertDoctorList.map(item => item.expertDoctorName).join(',')
          data.expertDoctorName = expertDoctorName
        }
        this.doctorList = (data.expertDoctorList || []).map(item => {
          return {
            ...item,
            type: '专家'
          }
        })
        this.applyForm = {
          ...data,
          statusName: statusMap[data.status],
        };
        this.logId = data.inquiryLogId;
        //获取患者信息
        let para = {
          id: data.inquiryLogId,
          webToken: this.$authInfo.webToken()
        };
        this.$ajax
          .getAllInfo(para)
          .then(res => {
            this.setPatientInfo(res)
          })
          .catch(err => {});


        /**
         * 初始化远程会诊的websocket
         */
        if (this.$authInfo.webToken()) {
          const wsuri = "wss://" + this.$global.remoteSocket;
          this.$setWsRemote.initWebSocket(wsuri, this.$authInfo.webToken());
        }
      })
    },
    setPatientInfo(res) {
      this.patientObj = res.data || {};
    },
    // 查看病例
    checkCase() {
      this.$nextTick(() => {
        if (this.$global.platform("lj")) {
          this.$refs.caseHistory.onOpen("his", this.patientObj);
        } else {
          if (this.$global.isNewCase) {
            this.$refs.caseHistory.onOpen("ca", this.patientObj);
          } else {
            this.$refs.caseHistory.onOpen("normal", {
              caseInfo: this.patientObj,
              idCard: this.patientObj.patientIdcard
            });
          }
        }
      });
    },
    // 发送图片
    senImage() {
      this.$refs.caseHistory.onOpen("pic", this.patientObj);
    },
    // 远程影像
    remoteVideo() {
      this.$message({
        message: "功能开发中",
        type: "warning"
      });
    },
    // 结束会诊
    closeRemote() {
      let that = this
      // 对话框关闭，输入意见
      this.$prompt("请输入会诊意见", "结束会诊", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "请输入会诊意见"
      })
        .then(({ value }) => {
          console.log('同意')
          try {
            that.$ajax.endConsultation({
              id: that.$route.query.id,
              proposal: value
            }).then(res => {
              that.$message({
                type: "success",
                message: "结束会诊成功"
              });
              that.$router.replace({
                name: "remoteConsult"
              });
            });
          } catch (e) {
            console.log('异常', e)
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消结束会诊"
          });
        });
    },
    handleRemark() {
      if (this.isExpert) {
        // 编辑弹窗
      } else {
        // 查看弹窗
      }
    },
    handleDiagnosis() {},
    handleHistoryPresentIllness() {},

    openMenu(data, e) {
      //是否弹出撤回功能
      this.msgData = data;
      let x = e.layerX;
      let y = e.layerY;
      this.top = y;
      this.left = x;

      var timeNow = this.formatDate(new Date());
      var timePass = data.msgDate;
      var date1 = new Date(timePass);
      var date2 = new Date(timeNow);
      var s1 = date1.getTime(),
        s2 = date2.getTime();
      var total = (s2 - s1) / 1000;
      var day = parseInt(total / (24 * 60 * 60)); //计算整数天数
      var afterDay = total - day * 24 * 60 * 60; //取得算出天数后剩余的秒数
      var hour = parseInt(afterDay / (60 * 60)); //计算整数小时数
      var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60; //取得算出小时数后剩余的秒数

      // var min = parseInt(afterHour / 60); //计算整数分
      // var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60; //取得算出分后剩余的秒数

      if (this.friendId == data.friendId) {
        if (afterHour > 120) {
          this.isWithdraw = false;
          this.$alert("消息发送已超过2分钟，不可进行撤回操作", "提示", {
            confirmButtonText: "确定",
            callback: action => {}
          });
        } else {
          this.isWithdraw = true;
        }
      } else {
        this.isWithdraw = false;
      }
    },
    withdrawHandle() {
      //撤回功能
      /**
       * 1	登录返回的信息
       * 2	未定义
       * 3	被邀请加入会诊
       * 4	接收到单条聊天信息
       * 5	未定义
       */
      let data = {
        msgUserName: this.applyForm.doctorName, //医生名称
        id: this.msgData.id, //信息id
        msgText: this.applyForm.doctorName + "医生撤回了一条消息", // 信息体
        friendId: this.friendId, // 接收方的用户imID
        inquiryLogId: this.logId, // 本次问诊的id
        msgType: 4, // 消息类型：0文字消息、1固定表情 3 图片url 4 撤回
        msgDate: this.formatDate(new Date()), // 发送时间
        packageType: 4
      };
      this.$setWsRemote.send(4, data);
      this.isWithdraw = false;
    },
    doctorSendMsg() {
      //发送信息
      if (this.sendMsgToPatient) {
        let data = {
          content: this.sendMsgToPatient,
          packageType: 4,
          contentType: 2,
          roomId: this.$route.query.id,
          timestamp: new Date().getTime()
        }
        this.$setWsRemote.send(4, data);
        this.sendMsgToPatient = "";
      }
      this.scrollContentBottom();
    },

    scrollContentBottom() {
      //聊天置于底部
      this.$nextTick(() => {
        setTimeout(() => {
          let msg = document.getElementById("scrollContent"); // 获取对象
          if (msg) msg.scrollTop = msg.scrollHeight; // 滚动高度
        }, 100);
      });
    },
    // 过滤日期格式
    formatDate(date, format) {
      if (format === undefined) {
        format = "YY-MM-DD hh:mm:ss";
      }
      var year = date.getFullYear(),
        month = date.getMonth() + 1, //月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
      var preArr = Array.apply(null, Array(10)).map(function(elem, index) {
        return "0" + index;
      });
      var newTime = format
        .replace(/YY/g, year)
        .replace(/MM/g, preArr[month] || month)
        .replace(/DD/g, preArr[day] || day)
        .replace(/hh/g, preArr[hour] || hour)
        .replace(/mm/g, preArr[min] || min)
        .replace(/ss/g, preArr[sec] || sec);
      return newTime;
    },
    closeMenu() {
      //关闭撤回
      this.isWithdraw = false;
    },
    createRoom() {
      this.$setWsRemote.send(5, {
        roomId: this.$route.query.id,
        packageType: 5,
        timestamp: new Date().getTime()
      });
    },
    inviteDoctorJoinRoom(message = false) {
      let inviteList = []
      if (this.isExpert) {
        // 专家那么剔除自己
        inviteList = this.doctorList.filter(item => item.expertDoctorId !== this.$authInfo.getUser().id)
        inviteList.push({
          expertDoctorId: this.applyForm.doctorId,
          expertDoctorName: this.applyForm.createBy,
          type: '医生'
        })
      } else {
        inviteList = this.doctorList
      }
      this.inviteList = inviteList
      inviteList.forEach(item => {
        console.log('邀请医生', item)
        let data = {
          receiverID: item.expertDoctorId, // 邀请人id
          receiverType: 'doctor', // 邀请人类型
          roomId: this.$route.query.id, // 房间id
          message: '邀请你加入会诊', // 邀请消息
          packageType: 2, // 包类型
          timestamp: new Date().getTime(), // 时间戳
        };
        this.$setWsRemote.send(2, data);
      })
      if (this.message) {
        this.$message({
          type: 'success',
          message: '邀请成功'
        })
      }
    },
    // 邀请病人
    invitePatientJoinRoom() {
      let data = {
        receiverID: this.applyForm.userId, // 邀请人id
        receiverType: 'P', // 邀请人类型
        roomId: this.$route.query.id, // 房间id
        message: '邀请患者加入会诊', // 邀请消息
        packageType: 2, // 包类型
        timestamp: new Date().getTime(), // 时间戳
      };
      this.$setWsRemote.send(2, data);
    }
  },
  created() {
    // 获取oss参数
    this.$ajax
        .uploadFileBridge({
          dir: "webpc/"
        })
        .then(res => {
          let { code, data } = res;
          if (code === 1) {
            console.log(data)
            this.ossParams = JSON.stringify(data)
          }
        })
        .catch(err => {
          this.$util.message(err.msg);
        });
    this.getDetail();
  }
};
</script>
<style lang="scss">
.box-card {
  display: flex;
  flex-direction: column;
  height: 100%;
  .el-card__body {
    height: 100%;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    padding: 12px;
  }
}

.my-user-box {
  min-width: 1200px;
  overflow: auto;
}
.meeting-box {
  flex-grow: 1;
  overflow: hidden;
  display: flex;
}
.remote-title {
  text-align: center;
  font-size: 18px;
  color: #333333;
  padding: 24px 0;
}
.handle-box {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  padding-left: 24px;
  .handle-item {
    border: 1px solid #409eff;
    border-radius: 4px;
    padding:10px 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-right: 12px;
    font-size: 12px;
    width: 45px;
    height: 45px;
    color: #409eff;
    cursor: pointer;
  }
}
.content {
  padding: 10px;
  .content-border {
    border: 1px solid;
    padding: 20px;
  }
  .operate {
    & > div {
      cursor: pointer;
    }
  }
  .start-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0 12px;
    cursor: pointer;
    position: relative;
    .consult-upload {
      position: absolute;
      left: 0;
      top: 0;
      width: 100% !important;
      height: 100%;
      opacity: 0;
    }
    img {
      width: 40px;
      height: 40px;
    }
  }
}
</style>

<style lang="scss" src="@/style/page/vedio.scss"></style>
